package net.xdclass.component;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.config.SmsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class SmsComponent {
    private static final String URL_TEMPLATE = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SmsConfig smsConfig;

    @Async("threadPoolTaskExecutor")
    public void send(String to, String templateId, String value) {
        long beginTime = System.currentTimeMillis();
        String url = String.format(URL_TEMPLATE, to, templateId, value);
        HttpHeaders headers = new HttpHeaders();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.set("Authorization","APPCODE "+smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                entity,
                String.class
        );
        long endTime = System.currentTimeMillis();
        log.info("url={},body={},time={}",url,response.getBody(),endTime-beginTime);
        if(response.getStatusCode().is2xxSuccessful()){
            log.info("短信发送成功,消耗时间={}ms",endTime-beginTime);
            log.info("验证码：{}",value);
        }else {
            log.error("短信发送失败:{}",response.getBody());
        }

    }
}

